<template>
  <div>
    <Header :user="user" :tenant="tenant" @toggle-password-modal="togglePasswordModal"/>
    <Sidebar :subsystems="subsystems" @logout="logout" @subsystem-click="switchSubsystem"/>
    <div class="main-content">
      <ul class="tab-links">
        <li v-for="tab in tabs" :key="tab.id" :class="{ active: activeTab.id === tab.id }" @click="selectTab(tab)">
          {{ tab.name }}
          <button @click.stop="closeTab(tab)">x</button>
        </li>
      </ul>
      <div class="tab-content">
        <component :is="activeTab.component"></component>
      </div>
    </div>
    <PasswordModal v-if="showPasswordModal" @close="togglePasswordModal(false)"/>
  </div>
</template>

<script>
import Header from '../components/HeaderBar.vue';
import Sidebar from '../components/SidebarMenu.vue';
import PasswordModal from '../components/PasswordModal.vue';

export default {
  components: { Header, Sidebar, PasswordModal },
  data() {
    return {
      showPasswordModal: false
    };
  },
  computed: {
    user() {
      return this.$store.state.user;
    },
    tenant() {
      return this.$store.state.tenant;
    },
    subsystems() {
      return this.$store.state.subsystems;
    },
    tabs() {
      return this.$store.state.tabs;
    },
    activeTab() {
      return this.$store.state.activeTab;
    }
  },
  methods: {
    logout() {
      this.$store.dispatch('logout');
      this.$router.push('/login');
    },
    switchSubsystem(subsystem) {
      this.$store.commit('setActiveSubsystem', subsystem);
      if (!this.tabs.some(tab => tab.id === subsystem.id)) {
        this.$store.commit('addTab', subsystem);
      }
      this.$store.commit('setActiveTab', subsystem);
    },
    openTab(menuItem) {
      if (!this.tabs.some(tab => tab.id === menuItem.id)) {
        this.$store.commit('addTab', { ...menuItem });
      }
      this.$store.commit('setActiveTab', menuItem);
    },
    selectTab(tab) {
      this.$store.commit('setActiveTab', tab);
    },
    closeTab(tab) {
      this.$store.commit('removeTab', tab);
      if (this.activeTab === tab) {
        this.$store.commit('setActiveTab', this.tabs.length ? this.tabs[0] : null);
      }
    },
    togglePasswordModal(show) {
      this.showPasswordModal = show;
    }
  }
};
</script>

<style scoped>
.tab-links {
  display: flex;
  list-style-type: none;
  padding: 0;
  margin: 0;
  border-bottom: 1px solid #ccc;
}

.tab-links li {
  padding: 10px 20px;
  cursor: pointer;
  position: relative;
}

.tab-links li.active {
  background: #eee;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}

.tab-links button {
  position: absolute;
  right: 5px;
  top: 5px;
  border: none;
  background: none;
  cursor: pointer;
}

.main-content {
  padding: 20px;
}

.tab-content {
  padding: 20px;
  background: #fff;
  border: 1px solid #ccc;
}
</style>